//
//  ForLeaseViewController.m
//  Rockval
//
//  Created by TuanNT on 4/28/14.
//  Copyright (c) 2014 TNL. All rights reserved.
//

#import "ForLeaseViewController.h"
#import "BuildingTableViewCell.h"
#import "DetailViewController.h"
#import "DataModels.h"

@interface ForLeaseViewController () <MKMapViewDelegate> {
	BOOL isShowingMap;
}
@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) NSArray *buildings;
@end

@implementation ForLeaseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	if (self) {
		// Custom initialization
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view.
//	[self showMenuBarButtonItem];
	[self setUpView];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	// Show the toolbar at the bottom
	[self.navigationController setToolbarHidden:NO animated:NO];
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

   #pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
	// Get the new view controller using [segue destinationViewController].
	// Pass the selected object to the new view controller.
	if ([segue.identifier isEqualToString:@"BuildingDetailSegue"]) {
		BuildingTableViewCell *cell = (BuildingTableViewCell *)sender;
		NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:cell.center];
		// Get object at indexpath and fill data to detail
		DetailViewController *vc = (DetailViewController *)[segue destinationViewController];
		vc.building = [self buildingAtIndexPath:indexPath];
	}
}

//================================ NAVIGATION ITEMS ================================
#pragma mark -
#pragma mark NAVIGATION ITEMS
//================================ TOOLBAR ITEMS ================================
#pragma mark -
#pragma mark TOOLBAR ITEMS

- (IBAction)btnViewType_TouchUpInside:(id)sender {
	isShowingMap = !isShowingMap;
	[self.mapView setHidden:!isShowingMap];
}

//================================ METHODS ================================
#pragma mark -
#pragma mark METHODS

- (void)setUpView {
	[self setTitle:@"For Lease - Near Me"];
	// Get sale data from server.
	[self getLeaseData];
}

- (void)getLeaseData {
	// Get watching list for sale data
//	NSString *userId = [DataManager sharedInstance].account.customerId;
//	[[DataManager sharedInstance] watchingListForLeaseWithCustomerId:userId andBlock: ^(NSArray *list) {
//	    // Update UI
//	    _buildings = [NSArray arrayWithArray:list];
//	    [self.tableView reloadData];
//	}];

	[[RCLocationManager sharedManager] startUpdatingLocationWithBlock: ^(CLLocationManager *manager, CLLocation *newLocation, CLLocation *oldLocation) {
	    NSString *lat = [NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];
	    NSString *longt = [NSString stringWithFormat:@"%f", newLocation.coordinate.longitude];
	    [[DataManager sharedInstance] leaseNearByWithLatitute:lat longtitute:longt andBlock: ^(NSArray *list) {
	        // Update UI
	        _buildings = [NSArray arrayWithArray:list];
	        [self.tableView reloadData];
		}];
	    [[RCLocationManager sharedManager] stopUpdatingLocation];
	} errorBlock: ^(CLLocationManager *manager, NSError *error) {
	    DLog(@"Do nothing");
	}];
}

- (Building *)buildingAtIndexPath:(NSIndexPath *)indexPath {
	return _buildings[indexPath.row];
}

/* Return the map view on MapTableViewCell */
- (MKMapView *)mapView {
	if (!_mapView) {
		_mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
		[_mapView setShowsUserLocation:YES];
		[_mapView setDelegate:self];
		[_mapView setBackgroundColor:[UIColor whiteColor]];
		[self.view addSubview:_mapView];
	}
	return _mapView;
}

#pragma mark -
#pragma MKMapKit Delegate

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
	DLog();
	// zoom and center on user location
	MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 8000000, 8000000);
	[self.mapView setRegion:region animated:NO];
	self.mapView.centerCoordinate = userLocation.location.coordinate;

	// Add an annotation
	for (Building *bd in _buildings) {
		MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
		point.coordinate = CLLocationCoordinate2DMake([bd.lat doubleValue], [bd.longProperty doubleValue]);
		point.title = bd.name;
		point.subtitle = bd.address;
		[self.mapView addAnnotation:point];
	}
}

//================================ UITABLEVIEW ================================
#pragma mark -
#pragma mark UITABLEVIEW

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSInteger count = 1;
	if (_buildings.count > 1) {
		count = _buildings.count;
	}
	return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell = nil;
	if (_buildings.count == 0) {
		cell = [tableView dequeueReusableCellWithIdentifier:@"EmptyTableViewCell"];
	}
	else {
		cell = [tableView dequeueReusableCellWithIdentifier:@"BuildingTableViewCell"];
		BuildingTableViewCell *buildingCell = (BuildingTableViewCell *)cell;
		Building *_bd = [self buildingAtIndexPath:indexPath];
		[buildingCell.buildingName setText:_bd.name];
		[buildingCell.price setText:_bd.price];
		[buildingCell.size setText:_bd.size];
		[buildingCell.type setText:_bd.main];
		[buildingCell.thumbnailImageView setImageWithURL:[NSURL URLWithString:[_bd.image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
		                     usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
	}
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
